package dao

import (
	"app/util/token"
	"errors"
)

type TokenMap map[string]interface{}

func CreateTokenString(id string, tm int64, validatetime int64, key string) string {

	obj := make(TokenMap)
	obj["userid"] = id
	obj["createtime"] = tm
	obj["validitytime"] = validatetime
	return token.CreateToken(key, obj)
}

func TokenParse(tokenString, key string) string {

	tk, ok := token.Parse(tokenString, key)

	if !ok {
		return ""
	}

	id, ok := token.GetsTokenfield(tk, "userid").(string)
	if !ok {
		return ""
	}
	return id
}

func (d *Dao) GetLicenseCode(id string, tm int64, validatetime int64) (code string, err error) {

	return CreateTokenString(id, tm, validatetime, d.cf.License.Code), nil
}

func (d *Dao) SetLicenseId(id string, v interface{}) error {

	return d.licensechannel.StringSet(d.cf.License.Session+id, v)
}

func (d *Dao) GetLicenseId(id string) (string, error) {

	value, err := d.licensechannel.StringGet(d.cf.License.Session + id)
	if err != nil {
		return "", errors.New("id no found")
	}
	return value, nil
}

func (d *Dao) SetLicenseIdTimeout(id string, tm int64) error {

	return d.licensechannel.Expire(d.cf.License.Session+id, tm)
}

func (d *Dao) IsExits(id string) bool {

	ok, _ := d.licensechannel.Exist(id)
	return ok
}
func (d *Dao) FindId(id string) error {

	value, err := d.GetLicenseId(id)
	if err != nil {
		return errors.New("id no found")
	}

	userid := TokenParse(value, d.cf.License.Code)

	if userid != id {
		return errors.New("id faild")
	}
	return nil
}
